import wx from 'weixin-js-sdk'
import api from "@/fetch/api"
import globalConfig from "@/config"
import router from "@/router"
//全局方法
export default {

  install(Vue, options) {
    /**
    *  储存localStorage
    */
    Vue.prototype.setlocalStorage = (storeName, storeData) => {
      var storeStr = JSON.stringify(storeData);
      var storeArr = window.localStorage.setItem(storeName, storeStr);
      return storeArr;
    },
      /**
      *  获取localStorage
      */
      Vue.prototype.getlocalStorage = (storeName) => {
        var storeName = localStorage.getItem(storeName);
        var storeArr = JSON.parse(storeName)
        return storeArr;
      },
      /**
      *  判断是否是微信端
      */
      Vue.prototype.isWinxin = () => {
        const ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
          return true;
        } else {
          return false;
        }
      },
      /**
      *  获取url后面的参数
      */
      Vue.prototype.getUrlParams = (name) => {
        var _reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"),
          _regNext = window.location.search.substr(1).match(_reg);
        if (_regNext != null) return decodeURI(_regNext[2]) || '';
        else return '';
      },
      /**
      *  获取用户信息
      */
      Vue.prototype.getUserInfo = () => {
        return JSON.parse(localStorage.getItem(globalConfig.companyUnique))
      },
      /**
      *  跳转
      */
      Vue.prototype.routeTo = (path) => {
        router.push(path)
      },
      /**
      *  手机号码正则
      */
      Vue.prototype.regexPhone = () => {
        return /^0?(13[0-9]|15[0-9]|18[0-9]|14[0-9]|17[0-9]|19[0-9])[0-9]{8}$/
      },

      /**
      *  微信分享
      */
      Vue.prototype.wxShare = (opts) => {
        const ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
          var that = this;
          const params = {
            url: window.location.href.split('#')[0]
          }
          api.wxSignature(params)
            .then(res => {
              console.log(res)
            })
            .catch(res => {
              console.log(res);
              var data = res.data;
              wx.config({
                debug: false,
                appId: data.appid,
                timestamp: data.timestamp,
                nonceStr: data.nonceStr,
                signature: data.signature,
                jsApiList: [
                  'onMenuShareTimeline',
                  'onMenuShareAppMessage',
                  'onMenuShareQQ',
                  'onMenuShareWeibo',
                  'onMenuShareQZone'
                ],
              });

              wx.ready(() => {
                //分享给朋友
                wx.onMenuShareAppMessage({
                  title: opts.title, // 分享标题
                  desc: opts.desc, // 分享描述
                  link: opts.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                  imgUrl: opts.img, // 分享图标
                  type: '', // 分享类型,music、video或link，不填默认为link
                  dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                  success: opts.success,
                  cancel: opts.cancel
                })

                //分享到朋友圈
                wx.onMenuShareTimeline({
                  title: opts.title, // 分享标题
                  link: opts.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                  imgUrl: opts.img, // 分享图标
                  success: opts.success,
                  cancel: opts.cancel
                })
              })
            })
        } else {
          console.log('非微信端，不做分享！')
        }
      },


      /**
      *  微信扫一扫
      */
      Vue.prototype.wxScanQRCode = (opts) => {
        const ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
          var that = this;
          const params = {
            url: window.location.href.split('#')[0]
          }
          api.wxSignature(params)
            .then(res => {
              console.log(res)
            })
            .catch(res => {
              console.log(res);
              var data = res.data;
              wx.config({
                debug: false,
                appId: data.appid,
                timestamp: data.timestamp,
                nonceStr: data.nonceStr,
                signature: data.signature,
                jsApiList: [
                  'scanQRCode',
                  'translateVoice'
                ],
              });

              wx.ready(() => {
                wx.scanQRCode({
                  needResult: 0, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                  scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                  success: function (res) {
                    var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                  }
                });
              })
              wx.error((err) => {
                console.log(err)
              })
              wx.complete((msg) => {
                console.log(msg)
              })
            })
        } else {
          console.log('非微信端，不能扫一扫！')
        }
      },

      /**
      *  微信支付
      */

      Vue.prototype.wxChooseWXPay = (data) => {
        console.log(data)
        const ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
          var that = this;
          const params = {
            url: window.location.href.split('#')[0]
          }
          wx.config({
            debug: false,
            appId: data.appId,
            timestamp: data.timestamp,
            nonceStr: data.nonceStr,
            signature: data.sign,
            jsApiList: [
              'chooseWXPay'
            ],
          });

          wx.ready(() => {
            wx.chooseWXPay({
              timestamp: data.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
              nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
              package: data.package,
              signType: "MD5", // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
              paySign: data.sign, // 支付签名
              success: function (res) {
                data.callback()
              },
              cancel: (err => {
                 data.errCallback()
              })
            });
          })
        } else {
          console.log('非微信端，不能支付！')

        }
      },


      /**
      *  暂未上线
      */
      Vue.prototype.TipsNotLine = () => {
        alert('功能开发中，稍后开放！')
      },


      /**
      *  金额保留两位小数点
      */
      Vue.prototype.toFixedStr = (str) => {
        return str.toFixed(2)
      },



      /**
      *  tags逗号隔开
      */
      Vue.prototype.splitTags = (str) => {
        if (str) {
          if (str.indexOf(',')) {
            var strs = str.split(",");
            return strs
          } else {
            return str
          }
        }
      },

      /**
      *  调起打电话
      */
      Vue.prototype.callPhone = (phone) => {
        window.location.href = `tel:${phone}`
      },


      /**
      *  判断是安卓还是ios端
      */
      Vue.prototype.navigatorAgent = () => {
        var u = navigator.userAgent,
          isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        if (isIOS) {
          return true
        } else {
          return false
        }
      },


      /**
      *  判断是否是Number
      */
      Vue.prototype.isNumber = (obj) => {
        var str = parseInt(obj)
        return typeof str === 'number' && !isNaN(str)
      },

      /**
      *  获取用户username
      */
      Vue.prototype.getUserId = () => {
        var userInfo = JSON.parse(localStorage.getItem(Vue.prototype.companyUnique))
        //alert(userInfo.username)
        return userInfo.username
        // return '18390143861';

      },
      /**
      *  获取用户ID
      */
      Vue.prototype.getUId = () => {
        var userInfo = JSON.parse(localStorage.getItem(Vue.prototype.companyUnique))
        return userInfo.id
        // return '198051';
      },
      /**
      *  获取用户openID
      */
      Vue.prototype.getOpenID = () => {
        var userInfo = JSON.parse(localStorage.getItem(Vue.prototype.companyUnique))
        return userInfo.openid
      },
      /**
      *  设置物流的请求地址
      */
      Vue.prototype.courierUrl = 'https://api.sailafeinav.com',

      /**
        * 格式化时间
        * @author yang
        * @param {String}  unixTime 时间戳
        **/
      Vue.prototype.TransformationTime = (unixTime) => {
        let attr = unixTime + ''
        console.log(parseInt(unixTime) * 1000)
        let time = attr < 13 ? new Date(parseInt(unixTime) * 1000) : new Date(parseInt(unixTime))
        if (time < new Date().getTime()) {
          console.log('传递的时间要大于当前时间')
          this.endHours = this.endMinutes = this.endSecnods = '00'
          return
        }
        let ymdhis = ""
        ymdhis += time.getFullYear() + "-"
        ymdhis += (time.getMonth() + 1) < 10 ? '0' + (time.getMonth() + 1) + "-" : (time.getMonth() + 1) + "-"
        ymdhis += time.getDate() < 10 ? '0' + time.getDate() : time.getDate()
        ymdhis += " " + time.getHours() < 10 ? " " + '0' + time.getHours() + ":" : " " + time.getHours() + ":"
        ymdhis += time.getMinutes() < 10 ? '0' + time.getMinutes() + ":" : time.getMinutes() + ":"
        ymdhis += time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()
        return ymdhis
      },
      Vue.prototype.fnOpenProDetail = (id) => {
          router.push({
            path: "goodslist_detail",
            query: {
              id: id
            }
          });
      }

  },
  // 判断当前访问是不是本地环境
  ENV() {
    if(window.location.hostname === 'localhost'){
      return true
    }

  }
}
